import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CodeSmsd } from './assets/codeSmsd.entity';
import { Repository } from 'typeorm';
import { util_Db_Add, util_Db_PageList } from '@/common/util/db';
import { Class_HttpException_Base } from '@/common/classes/httpException';
import { CodeSmsd_Create_SeClass, ICodeSmsd_FindLatest_SeClass } from './assets/codeSmsd.class';
import { CodeSmsd_Create_Dto } from './assets/codeSmsd.dto';
import { util_Index_RandomString } from '@/common/util/index';
import { SmsService_Service } from '../../commonModule/smsService/smsService.service';
import { Email_Service } from '../../commonModule/email/email.service';

@Injectable()
export class CodeSmsd_Service {
  constructor(
    @InjectRepository(CodeSmsd)
    private codeSmsd_Repository: Repository<CodeSmsd>,
    private smsService_Service: SmsService_Service,
    private email_Service: Email_Service,
  ) {}

  async codeSmsd_Create(body: CodeSmsd_Create_SeClass) {
    return await util_Db_Add({
      createDto: body,
      repository: this.codeSmsd_Repository,
    });
  }

  async codeSmsd_FindTen(query: ICodeSmsd_FindLatest_SeClass) {
    if (!query.email && !query.phone) throw new Class_HttpException_Base('参数错误');
    return await util_Db_PageList<CodeSmsd>({
      queryBuilder: this.codeSmsd_Repository.createQueryBuilder('code').orderBy('code.id', 'DESC'),
      query: {
        email: query.email,
        phone: query.phone,
        page: 0,
        size: 10,
      },
    });
  }

  async codeSmsd_Send(body: CodeSmsd_Create_Dto) {
    const { list, totalElements } = await this.codeSmsd_FindTen(body);
    if (list.length > 0) {
      if (new Date().getTime() - new Date(list[0].createTime).getTime() < 30000) {
        throw new Class_HttpException_Base('30秒内不得重复获取');
      }
      if (
        totalElements >= 10 &&
        new Date().getTime() - new Date(list[9].createTime).getTime() < 86400 * 1000
      ) {
        throw new Class_HttpException_Base('一天内不得超过10条验证码。');
      }
    }
    const vertifyCode = util_Index_RandomString({ length: 6, character: '0123456789' });
    if (body.phone) {
      const data = {
        phone: body.phone,
        code: Number(vertifyCode),
      };
      const result = await this.smsService_Service.smsService_Send(data);
      if (result == 'OK') await this.codeSmsd_Create(data);
    } else {
      const data = {
        email: body.email,
        code: Number(vertifyCode),
      };
      const result = await this.email_Service.email_SendEmail({ subject: '登录验证码', ...data });
      if (result == 'OK') await this.codeSmsd_Create(data);
    }
    return '发送成功';
  }
}
